import {useReducer} from "react";


const UseReducerCartPage = () => {
  console.log('11111'); // 为什么执行两次？

  // 初始化的值
  const initData = [
    {name: '小满(只)', price: 100, count: 1, id: 1, isEdit: false},
    {name: '中满(只)', price: 200, count: 1, id: 2, isEdit: false},
    {name: '大满(只)', price: 300, count: 1, id: 3, isEdit: false}
  ]
  type List = typeof initData

  // 集中处理状态state
  const reducer = (state: List, action: any) => {
    console.log('state:', state, 'action:', action);
    const currentItem = state.find(v => v.id === action.id)!
    console.log('currentItem:', currentItem);
    switch (action.type) {
      case 'add': // 数量+1
        currentItem.count++;
        return [...state]
      case 'sub': // 数量-1
        currentItem.count--;
        return [...state]
      case 'del': // 删除当前行
        return state.filter(v => v.id !== action.id)
      case 'edit': // 编辑当前行：商品名称可编辑
        currentItem.isEdit = !currentItem.isEdit;
        return [...state]
      case 'edit_name': // 编辑商品名称
        currentItem.name = action.newName
        return [...state]
      case 'blur': // 商品名称blur的触发。
        currentItem.isEdit = !currentItem.isEdit;
        return [...state]
      default:
        return state;
    }
  }

  // 定义状态
  const [goodsList, dispatch] = useReducer(reducer, initData)

  return (
    <>
      <div>
        <h2>购物车</h2>
        <table border={1} cellPadding={0} cellSpacing={0} width="100%">
          <thead>
          <tr>
            <th>ID</th>
            <th>商品</th>
            <th>单价</th>
            <th>数量</th>
            <th>总价</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          {goodsList.map(item => (
            <tr key={item.id}>
              <td>{item.id}</td>
              <td>{
                item.isEdit
                  ? <input
                    value={item.name}
                    onBlur={() => dispatch({type: 'blur', id: item.id})}
                    onChange={(e) => dispatch({type: 'edit_name', id: item.id, newName: e.target.value})}/>
                  : item.name
              }</td>
              <td>{item.price}</td>
              <td>{item.count}</td>
              <td>{item.count * item.price}</td>
              <td>
                <button onClick={() => dispatch({type: 'add', id: item.id})}>add</button>
                <button onClick={() => dispatch({type: 'sub', id: item.id})}>sub</button>
                <button onClick={() => dispatch({type: 'del', id: item.id})}>del</button>
                <button onClick={() => dispatch({type: 'edit', id: item.id})}>edit</button>
              </td>
            </tr>
          ))}
          </tbody>
          <tfoot>
          <tr>
            <td colSpan={4}>总价：</td>
            <td colSpan={2}>{goodsList.reduce((a, b) => a + b.price * b.count, 0)}</td>
          </tr>
          </tfoot>
        </table>
      </div>
    </>
  )
}

export default UseReducerCartPage;
